#!/bin/bash

if [ -z "$1" ]; then
	echo Pool UUID required as an argument. >&2
	exit 1
fi

POOL_UUID="$1"

i=0
while ! stratis-min pool is-stopped "$POOL_UUID" >/dev/null; do
	echo Waiting on pool with UUID $POOL_UUID...
	sleep 1
	if [ "$i" = 5 ]; then
		break
	fi
	i=$(($i + 1))
done

if $(stratis-min pool is-stopped "$POOL_UUID"); then
	if $(stratis-min pool is-bound "$POOL_UUID"); then
		if ! stratis-min pool start --unlock-method=clevis "$POOL_UUID"; then
			echo Failed to start pool with UUID $POOL_UUID using Clevis. >&2
			exit 1
		fi
	elif $(stratis-min pool is-encrypted "$POOL_UUID"); then
		if ! systemd-ask-password \
			"Enter password for pool with UUID $POOL_UUID" |
			stratis-min pool start --unlock-method=keyring --prompt "$POOL_UUID"; then
			echo Failed to start pool with UUID $POOL_UUID using passphrase. >&2
			exit 1
		fi
	else
		if ! stratis-min pool start "$POOL_UUID"; then
			echo Failed to start pool with UUID $POOL_UUID. >&2
			exit 1
		fi
	fi
fi

udevadm settle
